package org.jw.wishlist.resolver;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.jw.wishlist.entity.source.ItemSource;
import org.jw.wishlist.exception.LinkCodeParseFailedException;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author Jiawei Zhao
 */
@Slf4j
public class DouYinItemSourceResolver extends ItemSourceSupports implements ItemSourceResolver {

  private final ObjectMapper objectMapper = new ObjectMapper();

  public DouYinItemSourceResolver(RestTemplate restTemplate) {
    super(restTemplate);
  }

  @Override
  public ItemSource resolve(String linkCode) {

    String url = extractUrl(linkCode);
//    ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
    HttpHeaders headers = restTemplate.headForHeaders(url);
    String location = Optional.ofNullable(headers.getLocation())
        .map(URI::toString)
        .orElseThrow(() -> new LinkCodeParseFailedException("重定向地址为空"));

//    String res = entity.getBody();

    log.debug("location: {}", location);

    UriComponents components = UriComponentsBuilder.fromHttpUrl(URLDecoder.decode(location, StandardCharsets.UTF_8))
        .build();

    String detailSchema = components.getQueryParams().getFirst("detail_schema");
    UriComponents c1 = UriComponentsBuilder.fromUriString(URLDecoder.decode(detailSchema, StandardCharsets.UTF_8))
        .build();

    String metaParams = c1.getQueryParams().getFirst("meta_params");
    String decode = URLDecoder.decode(metaParams, StandardCharsets.UTF_8);

    try {
      String infoString = objectMapper.readTree(decode).get("entrance_info").toString();
      String objStr = infoString.substring(1, infoString.length() - 1);
      log.info(objStr);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }

//    log.debug("location: {}", entity.getHeaders().getLocation());
//    log.debug("返回值: {}", res);

    return null;
  }
}
